Page({
  data: {
    messages: [
      { id: 1, content: '您好，有什么可以帮您的吗？', isUser: false },
    ],
    inputValue: '',
    lastMessageId:"",
    toView: '', // 滚动到的目标视图 ID
    scrollTop: 0 // 滚动条位置
  },

  onInput(e) {
    this.setData({
      inputValue: e.detail.value
    });
  },
  sendMessage() {
    if (this.data.inputValue.trim() !== '') {
     
      const newMessage = {
        id: this.data.messages.length + 1,
        content: this.data.inputValue,
        isUser: true
      };
      this.setData({
        messages: [...this.data.messages, newMessage],
      });
      //ai回复
      wx.request({
        url: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=24.81d8de0a8aba80996bdbf4bbfb40108b.2592000.1719281320.282335-74932412',
        method:"POST",
        data:{
          "messages": [
            {"role":"user","content":this.data.inputValue}
           ],
            "system":"你是最优秀的中国移动的客服,你可以帮我解决任何关于业务以及回答我义务方面的问题"
        },
         success:(res)=>{
           const aiResponse = {
            id: this.data.messages.length + 1,
            content: res.data.result,
            isUser: false
          };
          this.setData({
                messages: [...this.data.messages, aiResponse],
                inputValue:''
              });
         }
      })
    }
  },onUnload(){
    console.log(this.data.messages);
    const messages = this.data.messages;
    console.log(messages);
    //将聊天记录保存到redis缓存中
    wx.request({
      url: 'http://192.168.2.18:9999/productOrder/historyChat',
      method:'POST',
      header:{
        "token":wx.getStorageSync('token')
      },
      data:{
        "chatMessages":messages,
        "id":wx.getStorageSync('id')
      },
      success:(res)=>{
        //将数据保存到redis缓存中        
        console.log(res);
      },fail:(res)=>{
        console.log(res);
      }
    })
  },
  onShow(){
  
    //查询用户聊天记录
    wx.request({
      url: 'http://192.168.2.18:9999/productOrder/getChatHistory',
      method:'GET',
      data:{
        id:wx.getStorageSync('id')
      },
      header:{
        "token":wx.getStorageSync('token')
      },
      success:(res)=>{
        console.log(res.data.data);
        if (res.data.data===null) {
          this.setData({
            messages: [{ id: 1, content: '您好，有什么可以帮您的吗？', isUser: false }]
          })
          return
        }
        //将数据保存到redis缓存中        
        this.setData({
          messages:res.data.data
        })
      },fail:(res)=>{
        console.log(res);
      }
    })
    console.log(1);
  }
});
